<template>
  <div id="maininfoeditpanel">
    <div style="height: calc(100% - 30px - 75px)" class="padding-lr-xs">
      <el-scrollbar style="height: calc(100%)">
        <!--fixme: 2024-12-9 为实现调取系统配置字体大小去掉title-width="60"-->
        <vxe-form ref="wlconfigpatsettingForm" class="form-pat-info margin-bottom form-size-auto " :class-name="form.isChk === 1 || form.isChk === 2 ? 'reviewed' : ''" title-align="left" :data="form">
          <vxe-form-item v-for="(item, index) in wonfigList.filter((data) => data.isVisiable == 1)" :title="item.fieldName" span="24" :field="item.fieldCode" :key="`formitem${index}`" :class-name="item.uiComponent === 'textarea' ? 'textarea-h' : ''">
            <template #default="params">
              <vxe-input v-enterNextInput :id="item.fieldCode" class="enterNextInputFlag" @blur="valueChange($event, item.fieldCode)" @clear="valueChange($event, item.fieldCode)" style="width: 100%" v-if="item.uiComponent === 'input'" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)" clearable></vxe-input>
              <!-- 有提示框 -->
              <el-tooltip class="item" effect="dark" :content="params.data[item.fieldCode]" placement="right" v-if="item.uiComponent === 'textarea' && item.fieldCode === 'DiagnosesDescription'">
                <div style='height: 220px'>
                  <vxe-textarea v-enterNextInput class="enterNextInputFlag" @blur="valueChange" style="width: 100%;" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)"></vxe-textarea>

                </div>
              </el-tooltip>
              <vxe-textarea v-enterNextInput class="enterNextInputFlag" @blur="valueChange($event, item.fieldCode)" style="width: 100%;height: auto" v-if="item.uiComponent === 'textarea' && item.fieldCode !== 'DiagnosesDescription'" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)"></vxe-textarea>
              <vxe-input v-enterNextInput class="enterNextInputFlag" @change="valueChange($event, item.fieldCode)" @clear="valueChange($event, item.fieldCode)" style="width: 100%" v-if="item.uiComponent === 'datepicker'" type="datetime" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)" clearable transfer></vxe-input>

              <vxe-input v-enterNextInput class="enterNextInputFlag" @blur="valueChange($event, item.fieldCode)" style="width: 100%" v-if="item.uiComponent === 'inputnumber'" type="number" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)" :step="0.1" :max="10"></vxe-input>

              <div v-if="item.uiComponent === 'agecomp'">
                <AgeComp class="enterNextInputFlag" :ageObj="{ age: params.data['age'], ageUnit: params.data['ageUnit'], secAge: params.data['secAge'], secAgeUnit: params.data['secAgeUnit'] }" :isDisabled="calcIsDisabled(item.isDisabled, item)" @ageChange="ageChange" />
              </div>

              <vxe-radio-group class="enterNextInputFlag" @change="valueChange($event, item.fieldCode)" style="width: 100%" v-if="item.uiComponent === 'radiogroup'" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)">
                <vxe-radio :label="itm.value" v-for="(itm, idx) in getArray(item.uiComponentResources)" :key="idx" :content="itm.label"></vxe-radio>
              </vxe-radio-group>

              <vxe-checkbox-group class="enterNextInputFlag" @change="valueChange($event, item.fieldCode)" style="width: 100%" v-if="item.uiComponent === 'checkboxgroup'" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)">
                <vxe-checkbox :label="itm.value" v-for="(itm, idx) in getArray(item.uiComponentResources)" :key="idx" :content="itm.label"></vxe-checkbox>
              </vxe-checkbox-group>

              <vxe-switch class="enterNextInputFlag" @change="valueChange($event, item.fieldCode)" style="width: 100%" v-if="item.uiComponent === 'switch'" v-model="params.data[item.fieldCode]" :disabled="calcIsDisabled(item.isDisabled, item)" open-label="是" close-label="否" :open-value="1" :close-value="0" active-color="#ff4949" inactive-color="#eeeeee"></vxe-switch>
              <VxePulldownSelection v-enterNextInput :isChild="false" :ref="'pdown' + index" :isDisabled="calcIsDisabled(item.isDisabled, item)" v-if="item.uiComponent === 'popoverselection'" :url="getCompRequestUrl(item)" @confirmClick="dropPullDownConfirm" :tableColumn="getCompShowFieldWidth(item)" :aimKeys="getCompFormTargetKeyMapper(item)" :displayTexts="['name']" :displayTextObj="form[item.fieldCode]" :dataObj="null" :isChangeName="getDataObj(item.selfUiComppropsoBJ, 'isChangeName')" @changeName="(value) => changeName(value, item.fieldCode)" />
              <VxeDictSelection v-enterNextInput :isChild="false" :tableColumn="[
                { field: 'code', title: '编码', width: `60px` },
                { field: 'name', title: '名称', minWidth: `80px` }
              ]" :url="`/api/sys/basDictDetail/findDictDetailList`" :ref="'dictpdown' + index" :isDisabled="calcIsDisabled(item.isDisabled, item)" v-if="item.isDict === 1 && item.fieldCode !== 'description'" :displayTextObj="params.data[item.fieldCode]" @confirmClick="dropSelectConfirm" :aimKeys="[{ targetField: item.fieldCode, sourceField: 'code' }]" :dataObj="{ code: dictTypeCode(item) }"></VxeDictSelection>

              <VxeRemarkDictSelection v-enterNextInput :isChild="false" :tableColumn="[
                { field: 'code', title: '编码', width: `60px` },
                { field: 'name', title: '名称', minWidth: `80px` }
              ]" :url="`/api/sys/basDictDetail/findDictDetailList`" :ref="'dictpdown' + index" :isDisabled="calcIsDisabled(item.isDisabled, item)" v-if="item.isDict === 1 && item.fieldCode == 'description'" :displayTextObj="params.data[item.fieldCode]" @confirmClick="remarkConfirm" :aimKeys="[{ targetField: item.fieldCode, sourceField: 'name' }]" :dataObj="{ code: dictTypeCode(item) }"></VxeRemarkDictSelection>
            </template>
          </vxe-form-item>
        </vxe-form>
      </el-scrollbar>
    </div>
    <vxe-input ref="hideFocusInputRef" style="display:none"></vxe-input>
    <ChkAuthComp ref="EditPanelChkAuthCompRef" @AuthSuccess="editPanelUpdateDoctor" @closeSHowApproveConfirm="authDialogClose" />
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted, defineProps, watch, ObjectDirective, isRef } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { formatDateTime, IsEmpty, sortByField } from '../utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';
import { LabMainInfoFields } from '@/utils/LabMainInfoFields';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import VxeDictSelection from '@/components/VxeDictSelection.vue';
import VxeRemarkDictSelection from '@/components/VxeRemarkDictSelection.vue';
import AgeComp from '@/components/AgeComp.vue';
// import func from '../../vue-temp/vue-editor-bridge';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';
import ChkAuthComp from '@/components/ChkAuthComp.vue';
import { AppStore } from '@/stores/store';
//import { elementSelectionKeys } from '@vue-flow/core/dist/utils';
let { proxy }: any = getCurrentInstance();
const store = AppStore();
let props = defineProps({
  currentMainInfoObj: {} as any
});
const font = reactive({
  color: 'rgba(0, 0, 0, .15)'
});
let editChkTestDoctorBefore: any = reactive({}); /**记录修改前的审核人，检验人 */
let form: any = reactive({});
let allowEditNotTodayMainInfo = ref(''); /**允许修改非当天的标本 */
let allowEditSigner = ref(''); /**允许修改签收人 */
let notAllowEditChk1 = ref(''); /**初审后是否允许修改标本信息 */
let allowEditBedNoOnlyZY = ref(''); /**只有住院病人才可输入床号 */
let notAllowEditPatType = ref(''); /**本报告单元不可修改病人类型 bkxgbrlx */
const EditPanelChkAuthCompRef = ref(null); /**弹窗验证 Ref对象 */
const hideFocusInputRef = ref(null); /**空闲焦点占用 */

//#region  监听属性
watch(
  () => props.currentMainInfoObj,
  (n, o) => {},
  { immediate: true, deep: true }
);

/**放到监听中的目的，已有记忆，再次重新选择时  此组件不会立马刷新 加watch解决立马刷新问题 */
watch(
  () => store.chkDoctorObj,
  (n, o) => {
    if (!IsEmpty(n.code)) {
      form.chkDoctor = n.code;
    }
    if (!IsEmpty(n.name)) {
      form.chkDoctorNa = n.name;
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => store.testDoctorObj,
  (n, o) => {
    if (!IsEmpty(n.code)) {
      form.testDoctor = n.code;
    }
    if (!IsEmpty(n.name)) {
      form.testDoctorNa = n.name;
    }
  },
  { deep: true, immediate: true }
);
//#endregion

// 方法定义区 =============
defineExpose({ getWkltConfigList, currentMainInfoChange, addMaininfo, editMaininfo });

let maininfoform = reactive([]) as any;

/**添加上机记录 */
async function addMaininfo(reqData: any) {
  if (IsEmpty(reqData.rptGroup) || IsEmpty(reqData.sampleda) || IsEmpty(reqData.sampleNo)) {
    return;
  }
  if (reqData !== null) {
    // for (let prop in reqData) {
    //   form[prop] = reqData[prop];
    // }
    Object.assign(form, reqData);
  }

  /**记忆上机人 审核人添加到 form */
  //#region 默认添加记忆的检验者  审核者
  let approveConfirmObj = {} as any;
  try {
    const approveConfirm = sessionStorage.getItem('locChkDoctor');
    if (IsEmpty(approveConfirm)) {
      //todo
    } else {
      approveConfirmObj = JSON.parse(approveConfirm);
      //验证是否过期
      const curDateTime = new Date().valueOf();
      if (Number(curDateTime) <= Number(approveConfirmObj.expressin)) {
        const a = 'chkDoctor';
        form[a] = approveConfirmObj.code;
      }
    }
  } catch (error) {
    //todo
  }
  try {
    const approveConfirm = sessionStorage.getItem('locTestDoctor');
    if (IsEmpty(approveConfirm)) {
      /**没有记忆，取当前登陆人的code  name */
      const locRemObj = localStorage.getItem('userInfo');
      if (!IsEmpty(locRemObj)) {
        const locRemObjEntry = JSON.parse(locRemObj);
        if (!IsEmpty(locRemObjEntry.username)) {
          form.testDoctor = locRemObjEntry.username;
        }
        if (!IsEmpty(locRemObjEntry.realname)) {
          form.testDoctorNa = locRemObjEntry.realname;
        }
      }
    } else {
      approveConfirmObj = JSON.parse(approveConfirm);
      //验证是否过期
      const curDateTime = new Date().valueOf();
      if (Number(curDateTime) <= Number(approveConfirmObj.expressin)) {
        const a = 'testDoctor';
        form[a] = approveConfirmObj.code;
      }
    }
  } catch (error) {
    //todo
  }
  //@endregion
  const formSaveObj = Object.assign({}, form);
  /**保存前验证是否已经存在该标本号的数据，防止同一个标本号在多台电脑扫码重复的问题 */
  const jgObjs = await validateIsExistMainInfo(form);
  const jgObj = jgObjs && jgObjs.length > 0 ? jgObjs[0] : null;
  if (jgObj && !IsEmpty(jgObj.patNa) && !IsEmpty(jgObj.reqNo)) {
    const type = await VXETable.modal.confirm(`该标本号已上机\n姓名: ${jgObj.patNa}\n条码号: ${jgObj.reqNo}\n上机时间: ${jgObj.createTime}\n上机人: ${jgObj.testDoctorNa}\n是否继续?`); /*不能改el  $confirm 回车事件冒泡你*/
    if (type === 'confirm') {
      //todo
    } else {
      //todo
      return;
    }
  }
  maininfoform.length = 0;
  proxy.$http
    .post('/lab/reqMain/insertMaininfoByReqNo', formSaveObj)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        maininfoform.push(res.data);
        currentMainInfoChange(res.data);
        //appendMainInfoToList(res.data);
        //向父组件传值
        proxy.$emit('changeMaininfo', maininfoform, 'insert');
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('数据存储异常', VxeNotifyType.error);
    });
}

/**更新上机记录 */
function editMaininfo(row, reqNo) {
  let data = {
    rptGroup: row.rptGroup,
    sampleNo: row.sampleNo,
    sampleda: row.sampleda,
    reqNo: row.reqNo === reqNo || IsEmpty(reqNo) ? null : reqNo,
    labMaininfo: row
  };
  maininfoform.length = 0;
  proxy.$http
    .post('/lab/reqMain/updateMaininfo', data)
    .then((res: any) => {
      console.log('updateMaininfo111111', res);

      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        // const i = labMainInfoList.findIndex((p) => p.id === row.id);
        // if (i > -1) {
        //   Object.assign(labMainInfoList[i], res.data);
        // } else {
        //   Object.assign(row, res.data);
        // }

        // proxy.$emit('quietRefreshRptresult');
        maininfoform.push(res.data);
        proxy.$emit('changeMaininfo', maininfoform, 'update');
        currentMainInfoChange(res.data);
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('更新检验记录失败11,请联系管理员' + err, VxeNotifyType.error);
    });
}

/**验证标本号是否已经创建 */
function validateIsExistMainInfo(labmaininfo) {
  return new Promise((resolve, reject) => {
    const url = '/lab/maininfo/validateIsExistMainInfo';
    proxy.$http
      .get(url, { params: { sampleNo: labmaininfo.sampleNo, rptGroup: labmaininfo.rptGroup, sampleDaStr: labmaininfo.sampleda } })
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.length > 0) {
          resolve(res.data);
        } else {
          resolve(null);
        }
      })
      .catch((err: any) => {
        resolve(null);
      });
  });
}

//#region  自定义指令
// 自定义指令
const enterNextInput: ObjectDirective<HTMLElement> = {
  mounted(el) {
    el.addEventListener('keypress', (e) => {
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      if (charcode == 13) {
        const doms: any = document.getElementsByClassName('enterNextInputFlag');
        let list = [];
        for (let i = 0; i < doms.length; i++) {
          let node = doms[i].childNodes;
          if (node.length > 0) {
            node.forEach((v) => {
              if ((v.nodeName == 'TEXTAREA' || v.nodeName == 'INPUT') && !v.disabled) {
                list.push(v);
              }
            });
          }
        }
        for (let j = 0; j <= list.length; j++) {
          if (list[j] == document.activeElement) {
            if (j == list.length - 1) {
              return;
            }
            list[j + 1].focus();
            return;
          }
        }
      }
    });
  }
};

// 使用自定义指令
proxy.$.directives = { enterNextInput: enterNextInput };
//#endregion

let wonfigList = reactive([]);

onMounted(() => {});

function getWkltConfigList(rptGroup: any) {
  wonfigList.length = 0;
  if (IsEmpty(rptGroup)) {
    wonfigList = LabMainInfoFields();
  } else {
    const url = '/lab/wlConfig/findWlConfigByRptGroup';
    const data = {
      suitModule: '1',
      rptGroup: rptGroup,
      type: 1
    };
    proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        if (res.data.length > 0) {
          wonfigList.push(...sortByField(res.data, 'displayOrder'));
        } else {
          wonfigList.push(...sortByField(LabMainInfoFields(), 'displayOrder'));
        }
      })
      .catch((err: any) => {
        wonfigList.push(...LabMainInfoFields());
      });
  }
}
/**检验记录行选中发生变化 */
function currentMainInfoChange(rowData) {
  /**可修改非当日标本数据 kxgfdrbbsj*/
  const a = getOptionValueByCodeGlobalOption('kxgfdrbbsj');
  allowEditNotTodayMainInfo.value = a;

  /**允许更改签收人 yxggqsr*/
  const b = getOptionValueByCodeGlobalOption('yxggqsr');
  allowEditSigner.value = b;

  /**初审后不可修改标本数据 yxggqsr*/
  const c = getOptionValueByCodeGlobalOption('cshbkxgbbsj');
  notAllowEditChk1.value = c;

  /**只有住院病人才可输入床号 zybrcksrch*/
  const d = getOptionValueByCodeRptGroupOption('zybrcksrch');
  allowEditBedNoOnlyZY.value = d;

  /**本报告单元不可修改病人类型 bkxgbrlx*/
  const e = getOptionValueByCodeRptGroupOption('bkxgbrlx');
  notAllowEditPatType.value = e;

  Object.keys(form).forEach((k) => {
    form[k] = null;
  });
  for (const key in rowData) {
    if (rowData[key]) {
      form[key] = rowData[key];
    }
  }

  /**检验人员记忆值 */
  if (IsEmpty(form.testDoctor) && IsEmpty(form.id)) {
    if (!IsEmpty(store.testDoctorObj.code)) {
      form.testDoctor = store.testDoctorObj.code;
    }
    if (!IsEmpty(store.testDoctorObj.name)) {
      form.testDoctorNa = store.testDoctorObj.name;
    }

    /**没有记忆，取当前登陆人的code  name */
    const locRemObj = localStorage.getItem('userInfo');
    if (!IsEmpty(locRemObj)) {
      const locRemObjEntry = JSON.parse(locRemObj);
      if (!IsEmpty(locRemObjEntry.username)) {
        form.testDoctor = locRemObjEntry.username;
      }
      if (!IsEmpty(locRemObjEntry.realname)) {
        form.testDoctorNa = locRemObjEntry.realname;
      }
    }
  }

  /**审核人员记忆 */
  if (IsEmpty(form.chkDoctor) && IsEmpty(form.id)) {
    if (!IsEmpty(store.chkDoctorObj.code)) {
      form.chkDoctor = store.chkDoctorObj.code;
    }
    if (!IsEmpty(store.chkDoctorObj.name)) {
      form.chkDoctorNa = store.chkDoctorObj.name;
    }
  }
}

function calcIsDisabled(v, m) {
  if (form && form.sampleda && !IsEmpty(form.sampleda)) {
    if (formatDateTime(form.sampleda, 'yyyy-MM-dd') !== formatDateTime(new Date().valueOf(), 'yyyy-MM-dd')) {
      /**可修改非当日标本数据 kxgfdrbbsj*/
      if (allowEditNotTodayMainInfo.value && (allowEditNotTodayMainInfo.value === '1' || allowEditNotTodayMainInfo.value === 1)) {
        //Skip
      } else {
        return true; //非当日标本信息 不能修改
      }
    }
  }

  /**初审后不可修改标本数据 */
  if (form && form.isChk && !IsEmpty(form.isChk)) {
    if (form.isChk === 1) {
      if (notAllowEditChk1.value && (notAllowEditChk1.value === '1' || notAllowEditChk1.value === 1)) {
        return true;
      }
    }
  }

  /**是否允许修改签收人 */
  if (m && m.fieldCode && !IsEmpty(m.fieldCode) && m.fieldCode === 'signer') {
    if (!allowEditSigner.value || (allowEditSigner.value !== '1' && allowEditSigner.value !== 1)) {
      return true;
    }
  }

  /**是否允许修改病人类型 */
  if (m && m.fieldCode && !IsEmpty(m.fieldCode) && m.fieldCode === 'patType') {
    if (!IsEmpty(notAllowEditPatType.value) && (notAllowEditPatType.value === '1' || notAllowEditPatType.value === 1)) {
      return true;
    }
  }

  /**住院病人才可以修改床号 */
  if (m && m.fieldCode && !IsEmpty(m.fieldCode) && m.fieldCode === 'bedNo') {
    if (!IsEmpty(allowEditBedNoOnlyZY.value) && (allowEditBedNoOnlyZY.value === '1' || allowEditBedNoOnlyZY.value === 1)) {
      if (form && form.patType && !IsEmpty(form.patType) && (form.patType === '3' || form.patType === 3)) {
        return false;
      } else {
        return true;
      }
    }
  }

  if (form.isChk === 2) {
    return true;
  }

  if (m.isEditHasSpecCode === 0 && !IsEmpty(form.reqNo)) {
    return true;
  }

  if (v) {
    return true;
  }

  return false;
}
function valueInputChange() {
  //todo
}
function getPropValue(val, propName = '', baseValue = '', item = null) {
  try {
    if (IsEmpty(val) || JSON.stringify(val) === '{}') {
      return '';
    }
    const pObj = JSON.parse(val);
    if (IsEmpty(pObj[propName])) {
      return '';
    }
    if (propName === 'fields') {
      return JSON.parse(pObj[propName]);
    }
    return baseValue + pObj[propName];
  } catch (error) {
    return '';
  }
}
/**组件请求路径 */
function getCompRequestUrl(item) {
  /**审核医师 */
  if (item.fieldCode === 'chkDoctor') {
    return `/api/user/getChkUserInfoList`;
  }
  /**检验医师 */
  if (item.fieldCode === 'testDoctor') {
    return `/api/user/getTestUserInfoList`;
  }
  /**科室名称 */
  if (item.fieldCode === 'reqDept') {
    return `/api/sys/findDepartmentListbyCurrentUserOrg`;
  }
  /**样本类型 */
  if (item.fieldCode === 'sampleType') {
    return `/api/lab/labSampleType/findSampleTypeList`;
  }
  /**申请医师 */
  if (item.fieldCode === 'reqDoctor') {
    return `/api/sys/hisEmployee/finAllHisEmployeeList`;
  }
  /**采样医师 */
  if (item.fieldCode === 'samplingDoctor') {
    return `/api/sys/hisEmployee/finAllHisEmployeeList`;
  }
  /**签收医师 */
  if (item.fieldCode === 'signerDoctor') {
    return `/api/user/getUserInfoList`;
  }
  /**打印医师 */
  if (item.fieldCode === 'printDoctor') {
    return `/api/user/getUserInfoList`;
  }
  /**初审医师 */
  if (item.fieldCode === 'firstChkDoctor') {
    return `/api/user/getUserInfoList`;
  }
  /**复核医师 */
  if (item.fieldCode === 'reChkDoctor') {
    return `/api/user/getUserInfoList`;
  }
  /**采样科室 */
  if (item.fieldCode === 'samplingDept') {
    return `/api/sys/findDepartmentListbyCurrentUserOrg`;
  }
}
/**组件展示字段，占比宽度 */
function getCompShowFieldWidth(item) {
  /**审核医师 */
  if (item.fieldCode === 'chkDoctor') {
    return [
      { field: 'username', title: '编码', width: '40%' },
      { field: 'realname', title: '名称', width: '60%' }
    ];
  }
  /**检验医师 */
  if (item.fieldCode === 'testDoctor') {
    return [
      { field: 'username', title: '编码', width: '40%' },
      { field: 'realname', title: '名称', width: '60%' }
    ];
  }
  /**科室名称 */
  if (item.fieldCode === 'reqDept') {
    return [
      { field: 'code', title: '编码', width: '40%' },
      { field: 'name', title: '名称', width: '60%' }
    ];
  }
  /**样本类型 */
  if (item.fieldCode === 'sampleType') {
    return [
      { field: 'sampleTypeCode', title: '编码', width: '40%' },
      { field: 'sampleTypeName', title: '名称', width: '60%' }
    ];
  }
  /**申请医师 */
  if (item.fieldCode === 'reqDoctor') {
    return [
      { field: 'code', title: '编码', width: '40%' },
      { field: 'name', title: '名称', width: '60%' }
    ];
  }
  /**采样医师 */
  if (item.fieldCode === 'samplingDoctor') {
    return [
      { field: 'code', title: '编码', width: '40%' },
      { field: 'name', title: '名称', width: '60%' }
    ];
  }
  /**签收医师 */
  if (item.fieldCode === 'signerDoctor') {
    return [
      { field: 'username', title: '编码', width: '40%' },
      { field: 'realname', title: '名称', width: '60%' }
    ];
  }
  /**打印医师 */
  if (item.fieldCode === 'printDoctor') {
    return [
      { field: 'username', title: '编码', width: '40%' },
      { field: 'realname', title: '名称', width: '60%' }
    ];
  }
  /**初审医师 */
  if (item.fieldCode === 'firstChkDoctor') {
    return [
      { field: 'username', title: '编码', width: '40%' },
      { field: 'realname', title: '名称', width: '60%' }
    ];
  }
  /**复核医师 */
  if (item.fieldCode === 'reChkDoctor') {
    return [
      { field: 'username', title: '编码', width: '40%' },
      { field: 'realname', title: '名称', width: '60%' }
    ];
  }
  /**采样科室 */
  if (item.fieldCode === 'samplingDept') {
    return [
      { field: 'code', title: '编码', width: '40%' },
      { field: 'name', title: '名称', width: '60%' }
    ];
  }
}
/**组件赋值字段 */
function getCompFormTargetKeyMapper(item) {
  /**审核医师 */
  if (item.fieldCode === 'chkDoctor') {
    return [{ formKey: 'chkDoctor', rowKey: 'username' }];
  }
  /**检验医师 */
  if (item.fieldCode === 'testDoctor') {
    return [{ formKey: 'testDoctor', rowKey: 'username' }];
  }
  /**科室名称 */
  if (item.fieldCode === 'reqDept') {
    return [{ formKey: 'reqDept', rowKey: 'code' }];
  }
  /**样本类型 */
  if (item.fieldCode === 'sampleType') {
    return [{ formKey: 'sampleType', rowKey: 'sampleTypeCode' }];
  }
  /**申请医师 */
  if (item.fieldCode === 'reqDoctor') {
    return [{ formKey: 'reqDoctor', rowKey: 'code' }];
  }
  /**采样医师 */
  if (item.fieldCode === 'samplingDoctor') {
    return [{ formKey: 'samplingDoctor', rowKey: 'code' }];
  }
  /**签收医师 */
  if (item.fieldCode === 'signerDoctor') {
    return [{ formKey: 'signerDoctor', rowKey: 'username' }];
  }
  /**打印医师 */
  if (item.fieldCode === 'printDoctor') {
    return [{ formKey: 'printDoctor', rowKey: 'username' }];
  }
  /**初审医师 */
  if (item.fieldCode === 'firstChkDoctor') {
    return [{ formKey: 'firstChkDoctor', rowKey: 'username' }];
  }
  /**复核医师 */
  if (item.fieldCode === 'reChkDoctor') {
    return [{ formKey: 'reChkDoctor', rowKey: 'username' }];
  }
  /**采样科室名称 */
  if (item.fieldCode === 'samplingDept') {
    return [{ formKey: 'samplingDept', rowKey: 'code' }];
  }
}
/**字典组件编码 */
function getCompDictCode(item) {}
function IsEmptyValidate(m, v) {
  //todo
}
function valueblur() {
  //todo
}
function getArray(val) {
  try {
    if (val === null || JSON.stringify(val) === '[]' || val.length <= 0) {
      return [];
    } else if (typeof val === 'string' && !val === null) {
      return JSON.parse(val);
    } else {
      return JSON.parse(val);
    }
  } catch (error) {
    return [];
  }
}
let dictArray = reactive([]);
let data = reactive({
  label: '',
  value: ''
});
/**
 * 字典获取数据Code
 */
function dictTypeCode(item) {
  // if (item && !IsEmpty(item.fieldCode)) {
  //   return item.dictCode;
  // }
  if (item && !IsEmpty(item.fieldCode) && item.fieldCode === 'patType') {
    return 'PATTYPE';
  }
  if (item && !IsEmpty(item.fieldCode) && item.fieldCode === 'sex') {
    return 'sex';
  }
  if (item && !IsEmpty(item.fieldCode) && item.fieldCode === 'description') {
    return 'BGZYMBZ';
  }
  return '!@#$QWE'; //无特别意义，仅是传字典中不存在的Code
}
function getDictArray(val) {
  try {
    if (val === null || val.length <= 0) {
      return [];
    } else {
      const url = '/api/sys/basDictDetail/findDictDetailList?code=' + val.toString();
      proxy.$http
        .get(url)
        .then((res: any) => {
          let dataList = res.data;
          dataList.forEach((item: any) => {
            dictArray.push({
              label: item.name,
              value: item.code
            });
          });
          return dictArray;
        })
        .catch((err: any) => {
          proxy.$alert(err, '提示');
        });
    }
  } catch (error) {
    return [];
  }
}
function valueChange(e, f = null) {
  if (IsEmpty(form.id) && IsEmpty(e.value)) {
    return;
  }
  if (f === 'patNo' && IsEmpty(form.patNo) && !IsEmpty(form.patType)) {
    /**删除病历号时清除病人类型 scblhsqcbrlx */
    const a = getOptionValueByCodeRptGroupOption('scblhsqcbrlx');
    if (a && (a === '1' || a === 1)) {
      form['patType'] = '';
    }
  }
  setTimeout(() => {
    saveForm();
  }, 300);
}
/**form值改变触发保存事件 */

function saveForm() {
  let data = {
    rptGroup: form.rptGroup,
    sampleNo: form.sampleNo,
    sampleda: form.sampleda,
    reqNo: form.reqNo,
    labMaininfo: form
  };
  proxy.$http
    .post('/lab/maininfo/updateMaininfo', data)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        //Object.assign(row, res.data);
        proxy.$emit('UpdateSuccessCallback', res.data);
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('修改病人信息失败,请联系管理员', VxeNotifyType.error);
    });
}
//获取目标赋值字段
function getAimKeys(item: any) {
  if (!IsEmpty(item)) {
    const pObj = JSON.parse(item);
    const b = 'fields';
    return pObj[b];
  } else {
    return [];
  }
}
function getDataObj() {
  return null;
}
function changeName(v1, v2) {
  return '';
}
/**
 * 下拉选择改变
 */
function pulldownSelectConfirm() {
  //todo
}
/**
 * 下拉选择确定时间【字典值】
 */
function dropSelectConfirm(e) {
  let isReCalcReferRange = false;
  if (e.isChild) {
    e.aimKeys.forEach((item) => {});
  } else {
    e.aimKeys.forEach((item) => {
      form[item.targetField] = e.row[item.sourceField];
      isReCalcReferRange = isReCalcReferRangeValidate(item);
    });
  }
  saveForm();
  if (isReCalcReferRange) {
    reCalcReferRange();
  }
}

function remarkConfirm(value) {
  form.description = value;
  saveForm();
}
/**
 * 下拉选择确定时间【常规】
 */
function dropPullDownConfirm(e) {
  const strKey = JSON.stringify(e.aimKeys);
  /**检验医师 */
  if (e.row && !IsEmpty(e.row.id) && strKey.indexOf('testDoctor') > -1) {
    Object.assign(editChkTestDoctorBefore, form);
    const mn = 'actFlag';
    editChkTestDoctorBefore[mn] = 'testDoctor';
    /**更改检验医师不需要密码验证 ggjyysbxymmyz */
    const a = getOptionValueByCodeGlobalOption('ggjyysbxymmyz');
    if (!a || (a !== '1' && a !== 1)) {
      if (EditPanelChkAuthCompRef.value) {
        EditPanelChkAuthCompRef.value.initPage(true, '检验', e.row, '2');
        return;
      }
    }
  }
  /**审核医师 */
  if (e.row && !IsEmpty(e.row.id) && strKey.indexOf('chkDoctor') > -1) {
    Object.assign(editChkTestDoctorBefore, form);
    const mn = 'actFlag';
    editChkTestDoctorBefore[mn] = 'chkDoctor';
    /**更改审核医师不需要密码验证 ggshysbxymmyz */
    const a = getOptionValueByCodeGlobalOption('ggshysbxymmyz');
    if (!a || (a !== '1' && a !== 1)) {
      if (EditPanelChkAuthCompRef.value) {
        EditPanelChkAuthCompRef.value.initPage(true, '审核', e.row, '2');
        return;
      }
    }
  }
  /**核对医师 */
  if (e.row && !IsEmpty(e.row.id) && strKey.indexOf('reChkDoctor') > -1) {
    Object.assign(editChkTestDoctorBefore, form);
    const mn = 'actFlag';
    editChkTestDoctorBefore[mn] = 'reChkDoctor';
    /**更改核对医师不需要密码验证 gghdysbxymmyz */
    const a = getOptionValueByCodeGlobalOption('gghdysbxymmyz');
    if (!a || (a !== '1' && a !== 1)) {
      if (EditPanelChkAuthCompRef.value) {
        EditPanelChkAuthCompRef.value.initPage(true, '核对', e.row, '2');
        return;
      }
    }
  }
  let isReCalcReferRange = false;
  if (e.isChild) {
    e.aimKeys.forEach((item) => {});
  } else {
    e.aimKeys.forEach((item) => {
      form[item.formKey] = e.row[item.rowKey];
      isReCalcReferRange = isReCalcReferRangeValidate(item);
    });
  }
  saveForm();
  if (isReCalcReferRange) {
    reCalcReferRange();
  }
}

/**计算是否需要重新计算参考范围 */
function isReCalcReferRangeValidate(item: any) {
  if (item.formKey === 'reqDept' || item.formKey === 'sex' || item.formKey === 'age' || item.formKey === 'sampleType' || item.formKey === 'phyCycel' || item.formKey === 'lactation' || item.formKey === 'patType' || item.targetField === 'reqDept' || item.targetField === 'sex' || item.targetField === 'age' || item.targetField === 'sampleType' || item.targetField === 'phyCycel' || item.targetField === 'lactation' || item.targetField === 'patType') {
    return true;
  }
  return false;
}

/**
 * 年龄改变事件
 * @ageObj 改变后的年龄
 */
function ageChange(ageObj) {
  Object.assign(form, ageObj);
  saveForm();
  reCalcReferRange(); //重新计算参考范围
}
/**验证医师授权码成功
 * @param e 验证成功返回值
 */
function editPanelUpdateDoctor(e) {
  proxy.$emit('validateTestChkDoctorSuccess', e);
  closeAllPulldownDropPanelSucc();
}
/**授权弹窗关闭 */
function authDialogClose() {
  closeAllPulldownDropPanel(); /**先关闭所有下拉选择 */
}
function closeAllPulldownDropPanel() {
  proxy.$nextTick(() => {
    const arr = proxy.$refs;
    for (const key in arr) {
      if (Object.prototype.hasOwnProperty.call(arr, key) && key.includes('pdown')) {
        const e = arr[key];
        if (e && e.length > 0 && e[0].hidePulldownPanel) {
          e[0].noShowPanel();
          e[0].hidePulldownPanel();
        }
      }
    }
    //hideFocusInputRef.value?.focus();
    returnBeforeValue();
  });
}
/**验证授权人成功时调用 */
function closeAllPulldownDropPanelSucc() {
  proxy.$nextTick(() => {
    const arr = proxy.$refs;
    for (const key in arr) {
      if (Object.prototype.hasOwnProperty.call(arr, key) && key.includes('pdown')) {
        const e = arr[key];
        if (e && e.length > 0 && e[0].hidePulldownPanel) {
          e[0].noShowPanel();
          e[0].hidePulldownPanel();
        }
      }
    }
    hideFocusInputRef.value?.focus();
  });
}
function returnBeforeValue() {
  if (editChkTestDoctorBefore && !IsEmpty(editChkTestDoctorBefore.actFlag)) {
    switch (editChkTestDoctorBefore.actFlag) {
      case 'testDoctor':
        form.testDoctor = '';
        form.testDoctorNa = '';
        setTimeout(() => {
          form.testDoctor = editChkTestDoctorBefore.testDoctor;
          form.testDoctorNa = editChkTestDoctorBefore.testDoctorNa;
        }, 50);
        break;
      case 'chkDoctor':
        form.chkDoctor = '';
        form.chkDoctorNa = '';
        setTimeout(() => {
          form.chkDoctor = editChkTestDoctorBefore.chkDoctor;
          form.chkDoctorNa = editChkTestDoctorBefore.chkDoctorNa;
        }, 50);
        break;
      case 'reChkDoctor':
        form.reChkDoctor = '';
        form.reChkDoctorNa = '';
        setTimeout(() => {
          form.reChkDoctor = editChkTestDoctorBefore.reChkDoctor;
          form.reChkDoctorNa = editChkTestDoctorBefore.reChkDoctorNa;
        }, 50);
        break;
    }
  }
}
/**姓名性别年龄等计算参考范围的条件改变时触发参考范围重新计算 */
function reCalcReferRange() {
  if (IsEmpty(form.id)) {
    return;
  }
  proxy.$http.post('/lab/rptResult/reCalcRptRssults', form).then((res: any) => {
    if (res && res.status && res.status.code && res.status.code === 200) {
      proxy.$emit('onlyRefreshRptResult');
    }
  });
}
</script>
<style lang="scss" scoped>
#maininfoeditpanel {
  height: 100%;

  :deep(.vxe-form--item-title) {
    width: 5em;
  }
}

.reviewed {
  background: url('@/assets/images/reviewed.png') no-repeat 90% 130px;
  background-size: 40%;
}

:deep(.vxe-form) {
  padding-left: 1px;

  .vxe-input--inner,
  .vxe-textarea--inner,
  .vxe-button {
    background-color: transparent;
  }

  .vxe-input--inner[disabled] {
    color: #000;
  }

  // 遮罩层
  .vxe-loading {
    background: transparent;

    .vxe-loading--chunk {
      top: 35px;
    }
  }
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #000 !important;
}

:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #000 !important;
}
</style>
